package com.example.estest.controller;

import com.example.estest.entity.User;
import com.example.estest.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author whx
 * @date 2022/7/2
 */
@RestController
@RequestMapping("user")
@AllArgsConstructor
public class UserController {

    private final UserRepository userRepository;

    private final ElasticsearchRestTemplate restTemplate;

    @GetMapping("getByName")
    public User getByName(String name){
        return userRepository.findByName(name);
    }

    @GetMapping("getAllByName")
    public List<User> getAllByName(String name){
        return userRepository.findAllByName(name);
    }

    @GetMapping("pageAllByName")
    public Page<User> pageAllByName(String name,int page,int size){
        return userRepository.findAllByName(name,PageRequest.of(page,size));
    }

    @GetMapping("queryByName")
    public User queryByName(String name){
        return userRepository.queryByName(name);
    }

    @PostMapping("save")
    public String add(@RequestBody User user){
        try{
            userRepository.save(user);
            return "保存成功";
        }catch (Exception e){
            e.printStackTrace();
            return "保存失败";
        }
    }

    @GetMapping("getByDepartmentName")
    public User getByDepartmentName(String name){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.nestedQuery("department_list",
                QueryBuilders.termQuery("department_list.name", name), ScoreMode.None))
                .withPageable(PageRequest.of(0,1));
        SearchHit<User> userSearchHit = restTemplate.searchOne(queryBuilder.build(), User.class);
        return userSearchHit == null ? null : userSearchHit.getContent();

    }

}
